#include "Framebuffer.h"

Framebuffer::Framebuffer()
{
	textureId = 0;
	framebufferId = 0;
	renderbufferId = 0;
}

Framebuffer::~Framebuffer(void)
{
	if (renderbufferId != 0)
		glDeleteRenderbuffersEXT(1, &renderbufferId);

	if (framebufferId != 0)
		glDeleteFramebuffersEXT(1, &framebufferId);
}

bool Framebuffer::Initialize(int width, int height, int bpp)
{
	glGenRenderbuffersEXT(1, &renderbufferId);
	glBindRenderbufferEXT(GL_RENDERBUFFER_EXT, renderbufferId);
	glRenderbufferStorageEXT(GL_RENDERBUFFER_EXT, GL_DEPTH_COMPONENT, width, height);
	glBindRenderbufferEXT(GL_RENDERBUFFER_EXT, 0);

	glGenFramebuffersEXT(1, &framebufferId);
	glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, framebufferId);
	glFramebufferRenderbufferEXT(GL_FRAMEBUFFER_EXT, GL_DEPTH_ATTACHMENT_EXT, GL_RENDERBUFFER_EXT, renderbufferId);

	glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, 0);
	return true;
}

void Framebuffer::StartRenderToTexture()
{
	glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, framebufferId);

	DWORD status = glCheckFramebufferStatusEXT(GL_FRAMEBUFFER_EXT);
	if (GL_FRAMEBUFFER_COMPLETE_EXT != status)
	{
		int x = 0;
	}
}

void Framebuffer::FinishRenderToTexture()
{
	glBindTexture(GL_TEXTURE_2D, 0);
	glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, 0);
}

UINT Framebuffer::GetTextureId()
{
	return textureId;
}

void Framebuffer::AttachColorTexture(UINT textureId)
{
	this ->textureId = textureId;

	glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, framebufferId);
	glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT0_EXT, GL_TEXTURE_2D, textureId, 0);
	glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, 0);
}

void Framebuffer::AttachDepthTexture(UINT textureId)
{
	glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, framebufferId);
	glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_DEPTH_ATTACHMENT_EXT, GL_TEXTURE_2D, textureId, 0);
	glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, 0);
}

void Framebuffer::RestoreDepthRenderBuffer()
{
	glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, framebufferId);
	glFramebufferRenderbufferEXT(GL_FRAMEBUFFER_EXT, GL_DEPTH_ATTACHMENT_EXT, GL_RENDERBUFFER_EXT, renderbufferId);
	glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, 0);
}
